package com.dstation.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
import com.aliyuncs.green.model.v20180509.VideoAsyncScanResultsRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.dstation.utils.uploader.ClientUploader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

public class IntelligenceExamine {

    /**
     * 上传视频到 阿里云检测,返回检测结果
     * @param
     * @param videoLength
     * @throws Exception
     */
    public static JSONObject uploadExamine(@RequestParam("videoName") String videoName, @RequestParam("videoLength") int videoLength)
            throws Exception {
        String videoFilePath = "D:/dStationData/video/";
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI5tBNLXT9bsFmie5BuUds", "RAULHd2zJ1eK0skMMCc4Ht1kyJISoK");
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
        videoAsyncScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
        videoAsyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。

        /**
         * 如果您要检测的文件存储在本地服务器上，可以通过下述代码生成URL作为视频地址传递到服务端进行检测。
         */
        String url = null;
        ClientUploader uploader = ClientUploader.getVideoClientUploader(profile, false);
        try{
            System.out.println(videoFilePath + videoName);
            url = uploader.uploadFile(videoFilePath + videoName);
        }catch (Exception e){
            e.printStackTrace();
        }

        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task = new LinkedHashMap<String, Object>();
        task.put("dataId", UUID.randomUUID().toString());
        task.put("url", url);
        task.put("interval", videoLength/8);   // 每个视频检测8次
        tasks.add(task);
        /**
         * 设置要检测的场景。计费是依据此处传递的场景计算。
         * 视频默认1秒截取一帧，您可以自行控制截帧频率。收费按照视频的截帧数量以及每一帧的检测场景进行计算。
         * 举例：1分钟的视频截帧60张，检测色情（对应场景参数porn）和暴恐涉政（对应场景参数terrorism）2个场景，收费按照60张色情+60张暴恐涉政进行计算。
         */
        JSONObject data = new JSONObject();
        data.put("scenes", Arrays.asList("porn", "terrorism"));
        data.put("tasks", tasks);
//        data.put("callback", "http://localhost:8080/video/callbackInterface");
//        data.put("seed", "abc_123");

        videoAsyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * 请务必设置超时时间。
         */
        videoAsyncScanRequest.setConnectTimeout(3000);
        videoAsyncScanRequest.setReadTimeout(10000);
        JSONObject jsonObject = null;
        try {
            HttpResponse httpResponse = client.doAction(videoAsyncScanRequest);

            if(httpResponse.isSuccess()){
                jsonObject = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(jsonObject, true));
            }else{
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


    /**
     * 根据taskId查看查询结果
     * @param taskId
     * @return
     * @throws Exception
     */
    public static JSONObject referExmaineRes(String taskId) throws Exception {
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI5tBNLXT9bsFmie5BuUds", "RAULHd2zJ1eK0skMMCc4Ht1kyJISoK");
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        VideoAsyncScanResultsRequest videoAsyncScanResultsRequest = new VideoAsyncScanResultsRequest();
        videoAsyncScanResultsRequest.setAcceptFormat(FormatType.JSON);

        List<String> taskList = new ArrayList<String>();
        // 这里添加要查询的taskId。提交任务的时候需要自行保存taskId。
        taskList.add(taskId);

        videoAsyncScanResultsRequest.setHttpContent(JSON.toJSONString(taskList).getBytes("UTF-8"), "UTF-8", FormatType.JSON);
        System.out.println("================debug");
        /**
         * 请务必设置超时时间。
         */
        videoAsyncScanResultsRequest.setConnectTimeout(3000);
        videoAsyncScanResultsRequest.setReadTimeout(6000);
        JSONObject jsonObject = null;
        System.out.println("================debug");
        try {
            HttpResponse httpResponse = client.doAction(videoAsyncScanResultsRequest);
            System.out.println("================debug");
            if(httpResponse.isSuccess()){
                jsonObject = JSON
                        .parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(jsonObject, true));
            }else{
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        System.out.println("================debug");
        return jsonObject;
    }

}